package net.sourceforge.m2settings.model;

import javax.swing.event.TableModelEvent;
import javax.swing.table.AbstractTableModel;

import org.apache.log4j.Logger;

public class MirrorsTableModel extends AbstractTableModel implements
		ExtendableTableModel {

	private static final long serialVersionUID = -57551943605459164L;

	public static final int COLUMN_ID = 0;

	public static final int COLUMN_NAME = 1;

	public static final int COLUMN_URL = 2;

	public static final int COLUMN_MIRROROF = 3;

	private static String[] columnTitles;

	private Logger log = Logger.getLogger(MirrorsTableModel.class);

	private Mirrors mirrors;

	public MirrorsTableModel(Settings userSettings) {
		log.debug("Create MirrorsTableModel with settings: "
				+ userSettings.toString());
		mirrors = userSettings.getMirrors();
		if (mirrors == null) {
			mirrors = new Mirrors();
		}
		columnTitles = new String[4];
		columnTitles[COLUMN_ID] = "id";
		columnTitles[COLUMN_NAME] = "name";
		columnTitles[COLUMN_URL] = "URL";
		columnTitles[COLUMN_MIRROROF] = "mirror of";
	}

	public Class<?> getColumnClass(int index) {
		return String.class;
	}

	public int getColumnCount() {
		return columnTitles.length;
	}

	public String getColumnName(int index) {
		return columnTitles[index];
	}

	public int getRowCount() {
		return mirrors.getMirrorCount();
	}

	public Object getValueAt(int rowIndex, int columnIndex) {
		Mirror row = mirrors.getMirror(rowIndex);
		switch (columnIndex) {
		case COLUMN_ID:
			return row.getId();
		case COLUMN_MIRROROF:
			return row.getMirrorOf();
		case COLUMN_NAME:
			return row.getName();
		case COLUMN_URL:
			return row.getUrl();
		}
		return null;
	}

	public boolean isCellEditable(int arg0, int arg1) {
		return true;
	}

	public void setValueAt(Object value, int row, int col) {
		Mirror mirror = mirrors.getMirror(row);
		assert (String.class == value.getClass());
		switch (col) {
		case COLUMN_ID:
			mirror.setId((String) value);
			break;
		case COLUMN_MIRROROF:
			assert (String.class == value.getClass());
			mirror.setMirrorOf((String) value);
			break;
		case COLUMN_NAME:
			mirror.setName((String) value);
			break;
		case COLUMN_URL:
			mirror.setUrl((String) value);
			break;
		}
	}

	public void addRow() {
		Mirror vMirror = new Mirror();
		mirrors.addMirror(vMirror);
		fireTableChanged(new TableModelEvent(this, getRowCount(),
				getRowCount(), TableModelEvent.ALL_COLUMNS,
				TableModelEvent.INSERT));
	}

}
